import React, { useState } from 'react';
import ProTable from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import { message, Modal, Popconfirm, Col, Table, Tag, Card } from 'antd';
import FormRender, { useForm } from 'form-render';
// 搜索 表头
import columnsData, { columnsDataType } from './data';
// 模拟的数据
import tableData from '../../mock/tableData';

import {
  getProcessDefinitionPageList,
  getProcessDefinitionStartForm,
  startProcessInstanceById,
} from '../../services/modelDefinition';
import { startProcessInstanceWithForm } from '../../services/processFormRepository';

import { flowableToFormEngine } from '../../utils/formSchemaTransform';

const ProcessDefinition = () => {
  const [launchModel, setLaunchModel] = useState(false);
  const [formSchema, setFormSchema] = useState({});
  const [processDefinition, setProcessDefinition] = useState({});
  const [formConfirmLoading, setFormConfirmLoading] = useState(false);

  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData;

  // 发起
  const initiate = async (record: any) => {
    // 查询判断是否有表单需要提交
    setProcessDefinition(record);
    let res = await getProcessDefinitionStartForm({
      processDefinitionId: record.id,
    });
    console.log(res);
    if (!res) {
      return message.error('获取发起表单信息失败');
    }
    // 没有则直接提交
    if (res.data == '') {
      let startRes = await startProcessInstanceById({
        processDefinitionId: record.id,
      });
      // console.log(startRes);
      if (startRes.code == '000000') {
        message.success('发起成功');
      } else {
        message.error('发起失败');
      }
      return;
    } else if (res.data != '') {
      // 有表单数据
      // 有表单则渲染表单
      let obj = flowableToFormEngine(res.data);
      // console.log(JSON.stringify(obj))
      setFormSchema(obj);
      setLaunchModel(true);
    }
  };

  // 取消发起
  const onCancel = () => {};

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      <li>
        <Popconfirm
          title={`是否发起？`}
          okText="是"
          cancelText="否"
          onConfirm={() => initiate(record)}
          onCancel={onCancel}
        >
          <a> 发起 </a>
        </Popconfirm>
      </li>
    </ul>
  );

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  const form = useForm();
  const onFinish = (formData: any, errors: any) => {
    // console.log('formData:', formData, 'errors', errors);
  };

  // 发起表单提交确认
  const handleOk = async () => {
    setFormConfirmLoading(true);
    let values = form.formData;
    console.log(processDefinition);

    let res = await startProcessInstanceWithForm({
      variables: values,
      processDefinitionId: processDefinition.id,
      outcome: '',
      name: processDefinition.name,
    });
    setFormConfirmLoading(false);
    if (res.code != '000000') {
      return message.error('发起失败');
    }
    message.success('发起成功');
    setLaunchModel(false);
  };

  // 发起表单提交取消
  const handleCancel = () => {
    setLaunchModel(false);
  };

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle="流程定义"
        scroll={{ x: 1000 }}
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={async (params) => {
          let res = await getProcessDefinitionPageList({
            ...params,
            pageNum: params.current,
          });
          if (res.code !== '000000') {
            message.error('获取模型管理表格信息失败');
          }
          const result = {
            data: res.data,
            total: res.pagination?.totalSize,
          };
          return result;
        }}
        // defaultData={tableData}
        rowKey="id"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'processDefinition',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
      />
      <Modal
        title="发起表单"
        open={launchModel}
        onOk={handleOk}
        onCancel={handleCancel}
        confirmLoading={formConfirmLoading}
      >
        <div style={{ margin: '0 20px 0 0' }}>
          <FormRender form={form} schema={formSchema} onFinish={onFinish} />
        </div>
      </Modal>
    </div>
  );
};

export default ProcessDefinition;
